package com.cqnu.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.cqnu.common.Constant;
import com.cqnu.entity.Paper;
import com.cqnu.entity.Student;
import com.cqnu.entity.commonModel.AjaxResult;
import com.cqnu.entity.commonModel.PageParameters;
import com.cqnu.util.DateUtils;

@Controller
@RequestMapping(value = "/fileHandle")
public class FileController extends BaseController {

	/**
	 * 文件上传
	 * 
	 * @throws IOException
	 * @throws IllegalStateException
	 */
	@RequestMapping(value = "/upLoadFile.do", method = RequestMethod.POST)
	@ResponseBody
	public AjaxResult upLoadFile(HttpServletResponse response,
			HttpServletRequest request) throws IllegalStateException,
			IOException {
		AjaxResult aj = new AjaxResult();
		
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());
		if (multipartResolver.isMultipart(request)) {
//			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
			//转换成多部分request  
		    MultipartHttpServletRequest multiRequest = multipartResolver.resolveMultipart(request); 
		    String thesisName = multiRequest.getParameter("thesisName");
		    
			Iterator<String> iter = multiRequest.getFileNames();
			while (iter.hasNext()) {
				MultipartFile file = multiRequest.getFile((String) iter.next());
				if (file != null) {
					String fileName = file.getOriginalFilename();

					String path1 = request.getSession().getServletContext().getRealPath("/")
							+ "download" + File.separator;

					// 下面的加的日期是为了防止上传的名字一样
					String srcName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + fileName;
					String path = path1 + srcName;

					File localFile = new File(path);

					file.transferTo(localFile);
					
					// 修改数据库
					Map<String, Object> map = this
							.getMap(new PageParameters(1));
					map.put("stu_id", ((Student) this.getSession(request,
							Constant.SESSION_USER_KEY)).getId().intValue());
					List<Paper> list = paperService.find(map);
					System.out.println(list.toString());
					if (list.size() != 0) {
						Paper paper = list.get(0);
						Student sessionInfo = (Student) this.getSession(
								request, Constant.SESSION_USER_KEY);
						paper.setStuId(sessionInfo.getId());
						paper.setSrc(srcName);
						paper.setTitle(fileName);
						paper.setCreattime(DateUtils.format(new Date(),
								"yyyy-MM-dd hh:mm:ss"));
						paper.setState(2);
						paper.setAchievement(0);
						int rs = paperService.update(paper); //上传一次为修改论文，不能添加，一个学生只能对应一个论文数据
						if( rs > 0 ){
							aj.setSuccess(true);
							aj.setMessage("上传成功！");
							return aj;
						}
					}
				}
			}
		}
		aj.setSuccess(false);
		aj.setMessage("上传失败！");
		return aj;
	}

	@RequestMapping(value = "/downLoadFile.do")
	public ResponseEntity<byte[]> download(HttpServletResponse response,
			HttpServletRequest request,
			@RequestParam("fileName") String fileName) throws IOException {
		response.setCharacterEncoding("utf-8");
		response.setContentType("multipart/form-data");
		response.setHeader("Content-Disposition", "attachment;fileName="
				+ fileName);
		try {
			String path = request.getSession().getServletContext().getRealPath("/")
					+ "download" + File.separator;
			// 这个download目录为啥建立在classes下的
			InputStream inputStream = new FileInputStream(new File(path
					+ fileName));
			System.out.println("  "+path
					+ fileName);
			OutputStream os = response.getOutputStream();
			byte[] b = new byte[2048];
			int length;
			while ((length = inputStream.read(b)) > 0) {
				os.write(b, 0, length);
			}

			// 这里主要关闭。
			os.close();

			inputStream.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		// 返回值要注意，要不然就出现下面这句错误！
		// java+getOutputStream() has already been called for this response
		return null;
	}
}
